package org.shiro.util;

import java.io.*;

/**
 * 序列化与反序列化工具类
 *
 * @author 党怡承
 * @version 1.0
 * @date 2021-04-24 8:38
 */
public class ByteSourceUtils {
  public static byte[] serialize(Object value) {
    if (value == null) {
      throw new NullPointerException("Can't serialize null");
    }
    byte[] bytes = null;
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    try {
      baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(value);
      oos.close();
      baos.close();
      bytes = baos.toByteArray();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      close(oos);
      close(baos);
    }
    return bytes;
  }

  public static Object deSerialize(byte[] bytes) {
    return deserialize(bytes, Object.class);
  }

  public static <T> T deserialize(byte[] bytes, Class<T>... requireTypes) {
    Object obj = null;
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
      if (bytes != null) {
        bais = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(bais);
        obj = ois.readObject();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      close(ois);
      close(bais);
    }
    return (T) obj;
  }

  private static void close(Closeable closeable) {
    if (closeable != null) {
      try {
        closeable.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
